import echarts from "echarts";
import zrender from "zrender";
import { createGradient } from "../color";
import { addCircleToChart } from "./base";
// import { toRad } from "../utils";
// import { animateRotate } from "./base";

const elements = {};

function draw(chart, percentage) {
  let gradient = new echarts.graphic.LinearGradient(1, 0.5, 0.5, 1, [
    { offset: 0, color: "rgba(5, 67, 136, 1)" },
    { offset: 1, color: "rgba(0, 204, 255, 1)" }
  ]);

  let zr = chart.getZr();
  let cx = zr.getWidth() / 2;
  let cy = zr.getHeight() / 2;

  // 这里使用一个透明的圆形放置text
  let text = new zrender.Circle({
    origin: [cx, cy],
    shape: {
      cx: cx,
      cy: cy,
      r: 40
    },
    style: {
      fill: null,
      fillOpacity: 0,
      strokeOpacity: 0,
      text: percentage + '%',
      fontSize: "20",
      textFill: "rgba(255, 255, 255, 0.8)"
    },
    z: 2
  });

  let option = {
    color: [gradient],
    angleAxis: {
      max: 100,
      show: false
    },
    radiusAxis: {
      show: false,
      type: "category",
      data: ['a', 'b', 'c'],
    },
    xAxis: {
      show: false
    },
    yAxis: {
      show: false
    },
    polar: {
      radius: ['60%', '100%']
    },
    tooltip: {
      // trigger: 'item'
      show: false
    },
    legend: {
      show: false
    },
    series: [
      {
        name: 'a',
        type: 'bar',
        coordinateSystem: 'polar',
        roundCap: true,
        barWidth: 15,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '40',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [percentage]
      },
    ]
  }

  let circles = drawSomeCircle(chart, percentage);
  chart.setOption(option);
  zr.add(text);

  elements.text = text;
  elements.chart = chart;
  elements.circles = circles;
  elements.__zr__ = zr;
}


function drawSomeCircle(chart, percentage) {

  let offsetAngle = 10
  let startAngle = (percentage / 100) * 360 - 90 + offsetAngle;
  let endAngle = 270 - offsetAngle

  let colorCount = 0
  for (let angle = startAngle; angle < endAngle; angle += 20) {
    colorCount += 1
  }

  let colors = createGradient('#0583A2', '#0B2931', colorCount)

  let circles = []

  for (let angle = startAngle, i = 0; angle < endAngle; angle += 20, i++) {
    let circle = addCircleToChart(chart, 50, 5, angle, false, colors[i])
    circles.push(circle)
  }

  return circles
}


function update(percentage) {
  let zr = elements.__zr__
  let chart = elements.chart

  elements.text.attr({
    style: {
      text: percentage + '%',
    }
  });

  elements.chart.setOption({
    series: [
      {
        name: 'a',
        data: [percentage]
      }
    ]
  });

  elements.circles.forEach(circle => {
    zr.remove(circle)
  });

  elements.circles = drawSomeCircle(chart, percentage)
}

export default {
  draw,
  update
}
